//
//  HYPlayerNode.m
//  SpriteKitDemo
//
//  Created by yanghaha on 16/4/4.
//  Copyright © 2016年 hillyoung. All rights reserved.
//

#import "HYPlayerNode.h"
#import "HYGeometry.h"
#import "PhysicsCategories.h"

#define KEY_wobbling @"wobbling"

@implementation HYPlayerNode

- (instancetype)init {
    if (self = [super init]) {
        self.name = [NSString stringWithFormat:@"Player %p", self];
        [self initNodeGraph];
        [self initPhysicsBody];
    }

    return self;
}

- (void)initNodeGraph {
    SKLabelNode *label = [SKLabelNode labelNodeWithFontNamed:@"Courier"];
    label.fontColor = [SKColor darkGrayColor];
    label.fontSize = 40;
    label.text = @"V";
    label.zRotation = M_PI;
    label.name = @"label";

    [self addChild:label];
}

- (void)initPhysicsBody {
    SKPhysicsBody *body = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(40, 40)];
    body.affectedByGravity = NO;
    body.categoryBitMask = PlayerCategory;
    body.contactTestBitMask = EnemyCategory;
    body.collisionBitMask = 0;

    self.physicsBody = body;
}

- (CGFloat)moveToward:(CGPoint)location {
    [self removeActionForKey:@"movement"];
    [self removeActionForKey:KEY_wobbling];

    CGFloat distance = HYPointDistance(self.position, location);
    CGFloat pixels = [UIScreen mainScreen].bounds.size.width;
    CGFloat duration = 2.*distance/pixels;

    [self runAction:[SKAction moveTo:location duration:duration] withKey:@"movement"];


    CGFloat wobbleTime = .3;
    CGFloat halfWobbleTime = wobbleTime*.5;

    SKAction *wobbling = [SKAction sequence:@[[SKAction scaleTo:.2 duration:halfWobbleTime],
                                              [SKAction scaleTo:1. duration:halfWobbleTime]]];
    NSUInteger wobbleCount = duration/wobbleTime;

    [self runAction:[SKAction repeatAction:wobbling count:wobbleCount] withKey:KEY_wobbling];



    return duration;
}

@end
